package com.panda.cn.controller;

import cn.hutool.core.codec.Base64;
import com.panda.cn.config.aspect.OperLog;
import com.panda.cn.config.aspect.OperLogType;
import com.panda.cn.config.property.CustomProperty;
import com.panda.cn.utils.file.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * 上传文件控制器
 *
 * @author Yanmh
 * @date 2022/09/14
 */
@Slf4j
@RestController
@RequestMapping(value = "/uploadFileCon")
public class UploadFileController {
    
    @Resource
    private CustomProperty customProperty;
    
    /**
     * 上传文件
     *
     * @param file 文件
     * @return {@link String}
     */
    @OperLog(operModul = "上传模块", operType = OperLogType._UPLOAD, operDesc = "上传文件")
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public String uploadFile(MultipartFile file){
        // 获取上传的路径
        String filePath = customProperty.getUploadUrl();
        // 上传
        File uploadFile = FileUtil.upload(file, filePath);
        // 路径
        String absolutePath = uploadFile.getAbsolutePath();
        // 加密后的字符串
        String filePathEncode = Base64.encode(absolutePath);
        return filePathEncode;
    }
    
    /**
     * 下载
     *
     * @param encode   编码
     * @param request  请求
     * @param response 响应
     */
    @OperLog(operModul = "下载模块", operType = OperLogType._UPLOAD, operDesc = "下载文件")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(String encode, HttpServletRequest request, HttpServletResponse response){
        // 解密字符串获取路径
        String filePath = Base64.decodeStr(encode);
        // 创建文件
        File file = new File(filePath);
        FileUtil.downloadFile(request, response, file, false);
    }
    
    
    
    
}
